<template>
  <div>
    <!-- 面包屑导航 -->
    <div class="center-w">
      <div class="head">
        <div class="title">商品管理</div>
        <el-button type="success" size="mini" @click="addCheckItem"
          >添加项目</el-button
        >
      </div>
      <el-table
        border
        :header-cell-style="{
          background: '#f3f6fa',
          color: '#555'
        }"
        height="87vh"
        size="mini"
        :data="checkList"
        style="overflow-y: auto;"
      >
        <el-table-column type="index" align="center"> </el-table-column>
        <el-table-column prop="name" label="项目">
          <template slot-scope="scope">
            <span> {{ scope.row.sort == -1 ? "额外项目" : "检查项目" }}：</span>
            <el-input
              style="width: 80%;"
              show-word-limit
              type="textarea"
              autosize
              size="small"
              placeholder="请输入"
              v-model="scope.row.name"
              clearable
              :disabled="scope.row.sort == -1 || scope.row.sort == 1"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          align="center"
          width="150"
          label="项目金额"
        >
          <template slot-scope="scope">
            <el-input
              show-word-limit
              size="small"
              oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
              placeholder="请输入"
              v-model="scope.row.price"
              clearable
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column
          prop="sort"
          align="center"
          width="150"
          label="排序顺序"
        >
          <template slot-scope="scope">
            <el-input
              style="width: 70px;"
              v-if="scope.row.sort != -1"
              show-word-limit
              size="small"
              placeholder="请输入"
              v-model="scope.row.sort"
              @blur="scope.row.sort = $event.target.value"
              oninput="value=value.replace(/[^\d]/g,'')"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" width="120" label="优惠券展示">
          <template slot-scope="scope">
            <el-switch
              @change="setCoupon(scope.row)"
              v-model="scope.row.state"
            ></el-switch>
            <span style="margin-left: 10px;">{{
              scope.row.state ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="120" label="是否为套餐">
          <template slot-scope="scope">
            <el-switch
              @change="setType(scope.row)"
              v-model="scope.row.type"
              :disabled="
                scope.row.sort == -1 ||
                  scope.row.sort == 1 ||
                  scope.row.id == 9 ||
                  scope.row.id == 34
              "
            ></el-switch>
            <span style="margin-left: 10px;">{{
              scope.row.type ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="120" label="是否支持砍一刀">
          <template slot-scope="scope">
            <el-switch
              @change="setCut(scope.row)"
              v-model="scope.row.isCut"
              :disabled="
                scope.row.sort == -1 ||
                  scope.row.sort == 1 ||
                  scope.row.id == 9 ||
                  scope.row.id == 34
              "
            ></el-switch>
            <span style="margin-left: 10px;">{{
              scope.row.isCut ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="sort"
          align="center"
          width="150"
          label="砍一刀最低百分比"
        >
          <template slot-scope="scope">
            <el-input
              style="width: 100px;"
              show-word-limit
              size="small"
              placeholder="请输入"
              v-model="scope.row.cutRate"
              @blur="scope.row.cutRate = $event.target.value"
              oninput="value=value.replace(/[^\d]/g,'')"
              clearable
            ></el-input>
            <span>%</span>
          </template>
        </el-table-column>
        <el-table-column width="180" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="submit(scope.row)"
              :type="scope.row.id ? 'primary' : 'success'"
              >{{ scope.row.id ? "编辑" : "新增" }}</el-button
            >
            <el-button
              size="mini"
              v-if="
                scope.row.sort != -1 &&
                  scope.row.sort != 2 &&
                  scope.row.sort != 9 &&
                  scope.row.sort != 10
              "
              type="danger"
              @click="deleteCurrentItem(scope.row, scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import {
  getGoodsList,
  addNewGoods,
  updateGoods,
  delectGoods
} from "../../api/goods";

export default {
  data() {
    return {
      checkList: [],
      otherObj: {}
    };
  },
  created() {
    this._getGoodsList();
  },

  methods: {
    // 获取商品列表
    async _getGoodsList() {
      let res = await getGoodsList();
      if (res.data && res.data.length > 0) {
        this.checkList = res.data;
        this.checkList.forEach(item => {
          if (item.type) {
            item.type = true;
          } else {
            item.type = false;
          }
          if (item.isCut) {
            item.isCut = true;
          } else {
            item.isCut = false;
          }
        });
      }
    },

    // 添加类目
    addCheckItem() {
      this.checkList.push({
        name: "",
        price: "",
        sort: "",
        amount: 0,
        state: false,
        type: false,
        isCut: false,
        profit: 0,
        cutRate: ""
      });
    },

    // 删除某个选项
    deleteCurrentItem(e, index) {
      this.$confirm("您确定要删除吗？", "删除确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定删除",
        cancelButtonText: "取消"
      })
        .then(() => {
          //这里判断是否有id 有的话就根据接口来处理删除，没有的话就按照下标来删除。
          if (e.id) {
            delectGoods(e.id).then(res => {
              if (res.code == 200) {
                this.$message.success("删除成功");
                this._getGoodsList();
              } else {
                this.$message.error("删除失败");
                this._getGoodsList();
              }
            });
          } else {
            this.checkList.splice(index, 1);
          }
        })
        .catch(action => {
          this.$message.info("取消删除");
        });
    },

    // 是否展示优惠券
    setCoupon(value) {
      console.log("val", value);

      this.$confirm(`确定展示该优惠券？`, "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          // const params = {
          //   id: value.id,
          //   state: value.state
          // };
          // updateGoods(params).then(res => {
          //   if (res.code == 200) {
          //     this.$message.success("切换成功");
          //     this._getGoodsList();
          //   } else {
          //     this.$message.error("切换失败");
          //     this._getGoodsList();
          //   }
          // });
          this.submit(value);
        })
        .catch(action => {
          this.$message.info("已取消");
          this._getGoodsList();
        });
    },

    // 是否是套餐
    setType(value) {
      this.$confirm(`确定设置为${value.type ? "套餐" : "普通"}？`, "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          // const params = {
          //   id: value.id,
          //   type: value.type ? 1 : 0
          // };
          // updateGoods(params).then(res => {
          //   if (res.code == 200) {
          //     this.$message.success("设置成功");
          //     this._getGoodsList();
          //   } else {
          //     this.$message.error("设置失败");
          //     this._getGoodsList();
          //   }
          // });
          this.submit(value);
        })
        .catch(action => {
          this.$message.info("已取消");
          this._getGoodsList();
        });
    },

    // 是否是套餐
    setCut(value) {
      this.$confirm(`确定${value.isCut ? "开启" : "关闭"}？`, "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          // const params = {
          //   id: value.id,
          //   isCut: value.isCut ? 1 : 0
          // };
          // updateGoods(params).then(res => {
          //   if (res.code == 200) {
          //     this.$message.success("设置成功");
          //     this._getGoodsList();
          //   } else {
          //     this.$message.error("设置失败");
          //     this._getGoodsList();
          //   }
          // });
          this.submit(value);
        })
        .catch(action => {
          this.$message.info("已取消");
          this._getGoodsList();
        });
    },

    //确定提交 根据item 是否有id来判断当前操作是编辑还是新增
    submit(item) {
      if (!item.name || item.price == "" || !item.sort)
        return this.$message.info("请填写完整的商品数据");
      item.type = item.type ? 1 : 0;
      item.isCut = item.isCut ? 1 : 0;
      item.cutRate = item.cutRate ? Number(item.cutRate) : null;
      if (item.id) {
        //编辑
        updateGoods(item).then(res => {
          if (res.code == 200) {
            this.$message.success("编辑成功");
            this._getGoodsList();
          } else {
            this.$message.error("编辑失败");
            this._getGoodsList();
          }
        });
      } else {
        //新增
        addNewGoods(item).then(res => {
          if (res.code == 200) {
            this.$message.success("新增成功");
            this._getGoodsList();
          } else {
            this.$message.error("新增失败");
            this._getGoodsList();
          }
        });
      }
    }
  }
};
</script>

<style scoped>
.names {
  color: rgba(16, 16, 16, 1);
  font-size: 20px;
  width: 250px;
  text-align: center;
  font-weight: 500;
}

.title {
  color: rgba(16, 16, 16, 1);
  font-size: 20px;
}

.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.sex {
  display: flex;
  align-items: center;
  margin: 10px 20px;
}

.btn {
  width: 200px;
  text-align: center;
}

.center-w {
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  background-color: #fff;
  height: 89vh;
  overflow-y: scroll;
  /* min-height: 1150px; */
  padding: 10px;
  border: 1px solid #ccc;
  /*margin: 20px;*/
}

.list-w {
  display: flex;
  align-items: center;
  /* border: 1px solid #f4f1f1; */
}

.sex div {
  color: rgba(109, 109, 109, 1);
  font-size: 16px;
  font-weight: 500;
}

.sex div:first-child {
  width: 150px;
  text-align: center;
}

.btn-s {
  margin-left: 35%;
  margin-top: 50px;
}
</style>
